<template>

	<view class="submit-task-page">
		<!-- 顶部栏 -->


		<!-- 任务信息 -->
		<view class="task-info">
			<view class="task-title-row">
				<text class="task-title">{{taskDetails.title}}</text>
				<text class="task-price">{{taskDetails.price}}</text>
			</view>
			<text class="task-desc">请按照任务要求提交哦亲</text>
		</view>

		<!-- 上传截图 -->
		<view class="section" v-if="taskDetails.is_attachment == 1">
			<view class="section-title">提交截图请在下方上传做任务的截图</view>
			<view class="upload-row">
				<button class="upload-btn" @click="handleUpload">上传图片</button>
				<button class="reset-btn" @click="resetUpload">重置</button>
			</view>
			<view v-if="previewUrls.length > 0" class="preview-container">
				<view v-for="(url, index) in previewUrls" :key="index" class="preview-item">
					<!-- <image :src="url" class="preview-image" mode="aspectFit" @click="previewImage(index)" /> -->
					<!-- <button class="delete-btn" @click="removeImage(index)">删除</button> -->
					<image :src="url" class="preview-image" mode="aspectFit" />
				</view>
			</view>
			<view class="clear-float"></view>
		</view>

		<!-- 提交数据 -->
		<view class="section section-gray">
			<view class="section-title">提交数据 请在下方填写做任务的数据</view>
			<view class="input-data-box">
				<input class="input-data" v-model="taskDetails.task_data" type="text" placeholder="请按要求提交文字验证信息..." />
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="footer-btn-row">
			<button class="footer-btn back-btn" @click="goBack">返回</button>
			<button class="footer-btn submit-btn" @click="subTask">提交任务</button>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app';
	import { addTaskOrder } from '@/api/task.js'
	import { Config } from '@/utils/config.js';
	const taskDetails = ref({
		title: '',
		price: '0.00',
		is_attachment: 1,
		id: 0,
		attachment:'',
		imgs:[],
		task_data:''
	})

	onLoad((options) => {
		console.log("onLoad options:", options);
		Object.assign(taskDetails.value, options);
		console.log(taskDetails.value);

	})

	const goBack = ()=>{
		uni.navigateBack();
	}

	const subTask = async() => {
		let res = await addTaskOrder(taskDetails.value).then(res => {
			// 提交任务逻辑
			uni.showToast({
				title: '任务提交成功',
				icon: 'success'
			})
			setTimeout(() => {
				goBack();
			}, 2000);
		}).catch(err => {
			console.error(err)
			uni.showToast({
				title: '提交失败，请稍后再试',
				icon: 'none'
			})
		});
	}

	const previewUrls = ref([]);   // 预览图地址数组
	const uploading = ref(false); // 上传状态
	const progress = ref(0);      // 上传进度

	// 选择图片
	const handleUpload = async () => {
	  try {
		// 1. 选择图片
		const res = await uni.chooseImage({
		  sizeType: ['compressed'],
		  sourceType: ['album', 'camera']
		});

		// 2. 显示预览
		previewUrls.value.push(...res.tempFilePaths);

		// 3. 执行上传
		uploading.value = true;
		const uploadPromises = res.tempFilePaths.map(filePath => uploadFile(filePath));
		const uploadResults = await Promise.all(uploadPromises);

		// 4. 处理结果
		console.log('服务器返回:', uploadResults);
		uni.showToast({ title: '上传成功' });

		// 保存上传后的图片地址
		taskDetails.value.imgs = [...taskDetails.value.imgs, ...uploadResults.map(result => result.data)];
	  } catch (err) {
		console.error('上传失败:', err);
		uni.showToast({ title: '上传失败', icon: 'error' });
	  } finally {
		uploading.value = false;
	  }
	};

	// 封装上传方法
	const uploadFile = (filePath) => {
	  return new Promise((resolve, reject) => {
		const task = uni.uploadFile({
		  url: Config.restUrl + '/upload',
		  filePath,
		  name: 'file',
		  header: { 'Authorization': uni.getStorageSync("token") || '' },
		  success: (res) => {
			if (res.statusCode === 200) {
			  resolve(JSON.parse(res.data));
			} else {
			  reject(new Error(`服务器错误: ${res.statusCode}`));
			}
		  },
		  fail: reject
		});
		// 进度监听
		task.onProgressUpdate((e) => {
		  progress.value = e.progress;
		});
	  });
	};

	const resetUpload = () => {
		previewUrls.value = [];
		taskDetails.value.imgs = [];
	}

</script>

<style lang="scss" scoped>
	.submit-task-page {
		min-height: 100vh;
		background: #f6f7fb;
		display: flex;
		flex-direction: column;
	}
	.task-info {
		background: #fff;
		padding: 24rpx 24rpx 12rpx 24rpx;
		border-bottom: 2rpx solid #f2f2f2;
	}
	.task-title-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 8rpx;
	}
	.task-title {
		font-size: 30rpx;
		color: #222;
		font-weight: bold;
	}
	.task-price {
		color: #ff4d00;
		font-size: 28rpx;
		font-weight: bold;
	}
	.task-desc {
		font-size: 22rpx;
		color: #bbb;
	}
	.section {
		background: #fff;
		padding: 18rpx 24rpx 24rpx 24rpx;
		border-bottom: 2rpx solid #f2f2f2;
	}
	.section-gray {
		background: #f6f7fb;
	}
	.section-title {
		font-size: 26rpx;
		color: #222;
		font-weight: bold;
		margin-bottom: 18rpx;
	}
	.upload-row {
		display: flex;
		align-items: center;
		gap: 18rpx;
	}
	.upload-btn {
		background: #1976d2;
		color: #fff;
		font-size: 26rpx;
		border-radius: 8rpx;
		padding: 0 32rpx;
		border: none;
	}
	.reset-btn {
		background: #f2f2f2;
		color: #222;
		font-size: 26rpx;
		border-radius: 8rpx;
		padding: 0 32rpx;

		border: none;
	}
	.input-data-box {
		background: #fff;
		border-radius: 12rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		padding: 0 18rpx;
		border: 2rpx solid #e0e0e0;
	}
	.input-data {
		width: 100%;
		border: none;
		background: transparent;
		font-size: 26rpx;
		color: #888;
		outline: none;
	}
	.footer-btn-row {
		display: flex;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100vw;
		z-index: 99;
	}
	.footer-btn {
		flex: 1;
		height: 90rpx;
		font-size: 32rpx;
		border: none;
		border-radius: 0;
		font-weight: bold;
	}
	.back-btn {
		background: #f2f2f2;
		color: #222;
	}
	.submit-btn {
		background: #4a90e2;
		color: #fff;
	}
	.preview-item{
		width: 25%;
		overflow: hidden;
		float: left;
	}
	.preview-item image{
		width: 100%;
		padding: 0;
		margin: 0;
	}
	.clear-float{
		clear: both;
	}
</style>
